<?php

namespace App\Http\Middleware;

use App\Models\Permissions;
use App\Models\Users;
use Closure;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Str;

class Permission
{

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {

        return $next($request);
        //dump(auth()->user()->getMenus());
       //dump(auth()->user()->allPermissions()->toArray());

       // dump(auth()->user()->manyRoles->toArray());
        //dump(auth()->user()->isRoot());
       // dump(auth()->user()->allPermissions()->toArray());

       // $route = Route::currentRouteName();
      //  dump($route);

        //dump(auth()->user()->hasPermission($permission->name));

        if(auth()->user()->manyRoles->isEmpty())
        {
            return response()->view('errors.403', ['status' => "当前用户未角色授权，请联系相关管理人员!"]);
        }
        //是否有超级管理员，是则不则行权限验证
        if (auth()->user()->isRoot())
        {
            return $next($request);
        }

        /****************************************
         * 获取当前路由的别名，如果没有返回 null
         * （不在 laravel 中使用时，可以获取当前 url）
         ****************************************/
        $route = Route::currentRouteName();

        // 判断权限表中这条路由是否需要验证
        if ($permission = Permissions::where('slug', $route)->first()) {
            //dump($permission->name);
            // 当前用户不拥有这个权限的名字
            if (! auth()->user()->hasPermission($permission->slug)) {

                if ($request->isMethod('ajax')) {
                    return response()->json([
                        'code'=>0,
                        'msg'=>'登录已过期，请重新登录'
                    ]);
                } else {
                    return response()->view('errors.403', ['status' => "权限不足，需要：{$permission->name}权限"]);
                }
            }
        }

        return $next($request);
    }
}
